﻿using ConsumeSys.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace ConsumeSys.Controllers
{
    public class UserLoginController : BaseController
    {
        /// <summary>
        /// 实例化用户业务逻辑
        /// </summary>
        private BLL.UserBLL bll_UserBLL = new BLL.UserBLL();

        /// <summary>
        /// 用户登录页面
        /// </summary>
        /// <param name="ToUrl">返回地址</param>
        /// <returns></returns>
        public ActionResult Login(string ToUrl)
        {
            ViewData["ToUrl"] = ToUrl;
            return View();
        }

        /// <summary>
        /// 用户登录提交地址
        /// </summary>
        /// <param name="username">用户名或手机号码</param>
        /// <param name="password">登录密码</param>
        /// <returns></returns>
        public async Task<JsonResult> SubmitLogin(string username, string password)
        {
            Model.User _user = null;
            HttpContextBase context = HttpContext;
            await Task.Run(() =>
            {
                RSACrypto rsad = new RSACrypto(SysConfigKey.rsa_private_key_1024, SysConfigKey.rsa_public_key_1024);
                string pwd_decry = rsad.Decrypt(password);
                _user = bll_UserBLL.GetLoginUser(username, pwd_decry);
            });
            try
            {
                if (_user != null && _user.id > 0)
                {
                    //登录成功
                    //Common.Globals.SetLoginUserCookie(_user.u_UserName);
                    HttpCookie cookie = new HttpCookie(Globals.loginUserCookieKey, DESEncrypt.Encrypt(_user.u_UserName));
                    cookie.Expires = DateTime.Now.AddHours(8).AddMinutes(120);
                    context.Response.SetCookie(cookie);
                    return Json(new { state = "success", msg = "登录成功" });
                }
                else
                {
                    return Json(new { state = "fail", msg = "账号或密码错误" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { state = "fail", msg = ex.Message });
            }
        }

        /// <summary>
        /// 注销
        /// </summary>
        /// <returns></returns>
        public ActionResult ExitLogin()
        {
            Common.Globals.ExitLoginUser();
            return RedirectToAction("Login");
        }
    }
}
